package com.scalar.chiptrack.rma.actions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import java.io.FileWriter;
import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.Mailer;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.operations.process.dao.NewVendorLocationDAO;
import com.scalar.chiptrack.commons.Address;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.rma.RMALineItem;
import com.scalar.chiptrack.rma.RMAUtil;
import com.scalar.chiptrack.rma.dao.RmaDAO;
import com.scalar.chiptrack.rma.forms.RMAForm;
import com.scalar.chiptrack.sales.Customer;
import com.scalar.chiptrack.sales.SalesOrder;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.CustomerRelationshipDAO;
import com.scalar.chiptrack.sales.dao.SalesDAO;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.dao.UserDAO;
import com.scalar.ScalarException;

public final class RMAFormAction extends ChipTrackAction
{
    private String customerName = null;
    private ArrayList customersList = new ArrayList();
    public static String ACTION_NAME = "/generateRMA.do";

    public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws Exception
    {
		String action = request.getParameter( "action" );
        boolean success = false;
        RMAForm subform = ( RMAForm ) form;
        HttpSession session = request.getSession();
        if( action == null )
        {
            action = "GetAll";
        }
        User user = ( User ) session.getAttribute (SessionKeys.USER_KEY);
        if( user == null )
        {
            if( "ConfirmForm".equals(action) || "SaveForm".equals(action) || action == null )
            {
                session.setAttribute (SessionKeys.SOURCE_PAGE_KEY, "/rma.do");
            }
            else
            {
                session.setAttribute (SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString());
            }
            return (mapping.findForward ("login"));
        }
        if ( user != null )
        {
            if ( user.isActionAllowed ( Functionality.RMA_FORM, User.USER_ACTION_MODIFY ) )
            {
                request.setAttribute ( "showMessage", "FALSE" );
            }
            else
            {
                request.setAttribute ( "showMessage", "TRUE" );
            }
        }

        String showModify = "FALSE";
        String showDelete = "FALSE";
        HashMap errors = new HashMap();
		HashMap info = new HashMap();
        
        if( user.isActionAllowed( Functionality.RMA_FORM, User.USER_ACTION_MODIFY ) )
        {
            showModify = "TRUE";
        }
        if( user.isActionAllowed( Functionality.RMA_FORM, User.USER_ACTION_DELETE ) )
        {
            showDelete = "TRUE";
        }

        request.setAttribute( "showModify" ,showModify);
        request.setAttribute( "showDelete" ,showDelete);


		if( "CreateForm".equals( action ) )
        {
        	//This part of the code mainly depend on the modules. If third party tool is interacting with ChipTrac we need change this part.
			String customerId = ( String )request.getParameter("customerId");
            int maxLineItemNo           = 8;
            if( customerId ==  null)
            {
                customerId = ( String ) request.getAttribute("customerId");
			}
			//If we are interacting with some other module we need to bring the customers from that module. Please look into this part carefully when u are integrating with other module.
			//I am assuming now integrated with ChipTrac sales, customer details comes from the Customer table.
			Customer customer = null;
			customer = CustomerDAO.getCustomerDetails ( Integer.parseInt( customerId ) );

			RMAUtil.setCustomerDetailsFromChipTrac( subform, customer );

            request.setAttribute ( "customers", customer);
			request.setAttribute ( "lineItems", getRmaLineItems());
            request.setAttribute( "maxLineItemNo", Integer.toString( maxLineItemNo ) );
            request.setAttribute ( "endUserList", CustomerRelationshipDAO.getAllOdmsForCustomer( subform.getCustomerId()+""  ) );
            //session.setAttribute ( "vendorDetails", VendorDAO.getVendorNamesByProcessByUserType( null, Constants.LOCATION_TYPE_FINISHED_GOODS, null ) );
            session.setAttribute( "vendorDetails", NewVendorLocationDAO.loadVendorsByPSType( null, Constants.LOCATION_TYPE_FINISHED_GOODS ) );
            request.setAttribute ( "mfgParts", SalesOrderDAO.loadAllManfacturingPartNumbers () );

            HashMap VendorAddressMap = NewVendorLocationDAO.getVendorAddressDetailsMap(Constants.LOCATION_TYPE_FINISHED_GOODS );
            subform.setVendorAddressMap( VendorAddressMap );
		}
        else if( "UpdateRMAForm".equals( action ) )
        {
        	String rmaId                = request.getParameter("rmaId");
            String rmaLineItemStatus    = "";
            int maxLineItemNo           = 1;
			ArrayList list              = null;

            RmaDAO.getRmaDetails( subform, rmaId );
            request.setAttribute ( "mfgParts", SalesOrderDAO.loadAllManfacturingPartNumbers() );

			list = RmaDAO.getRmaLineItemDetails( rmaId );

            request.setAttribute( "rmaCanCancel", new Boolean( true ) ); //To Know whether atleast one line item is Closed, if so setting request attribute to False, otherwise True

            for ( int i = 0; i < list.size(); i++ )
            {
                RMALineItem rmaLineItem = ( RMALineItem ) list.get(i);
                if ( rmaLineItem != null )
                {
                    rmaLineItemStatus = rmaLineItem.getStatus();
                    if ( rmaLineItemStatus != null && rmaLineItemStatus.equalsIgnoreCase("CLOSE") )
                    {
                        request.setAttribute( "rmaCanCancel", new Boolean ( false ) );
                        break;
                    }
                }
            }
            maxLineItemNo = RmaDAO.loadMaxLineItemNo(rmaId);

            if(!list.isEmpty())
            {
				request.setAttribute( "lineItems", list );
                subform.setLineItemList( list );
            }
            else
            {
                maxLineItemNo = 8;
				request.setAttribute( "lineItems", getRmaLineItems() );
			}
            Address address = CustomerDAO.getAddress( subform.getBillingAddressId() );

            if( address == null )
            {
                address = new Address();
            }
            session.setAttribute( "rmaBillingAddress" , address );
            //session.setAttribute( "vendorDetails", VendorDAO.getVendorNamesByProcessByUserType ( null, Constants.LOCATION_TYPE_FINISHED_GOODS, null ) );
            session.setAttribute( "vendorDetails", NewVendorLocationDAO.loadVendorsByPSType( null, Constants.LOCATION_TYPE_FINISHED_GOODS ) );

            request.setAttribute( "maxLineItemNo", Integer.toString( maxLineItemNo ) );
            request.setAttribute( "rmaId" , rmaId );
            request.setAttribute( "endUserList", CustomerRelationshipDAO.getOdmsForChangeSalesOrder( subform.getCustomerId() + "" , subform.getEndUserID() + "" ) );

            HashMap VendorAddressMap = NewVendorLocationDAO.getVendorAddressDetailsMap( Constants.LOCATION_TYPE_FINISHED_GOODS );
            subform.setVendorAddressMap( VendorAddressMap );

            if( "CLOSE".equalsIgnoreCase( subform.getRmaStatus() ) )
            {
                return ( mapping.findForward( "viewForm" ) );
            }
            return ( mapping.findForward ( "rmaIssue" ) );
		}
        else if("IssueForm".equals( action ) )
        {
        	int rmaId = 0;
			try
            {
				DBTransaction dbTransaction = null;
				dbTransaction = DBTransaction.getInstance();
				dbTransaction.begin();
                String host = request.getHeader ( "HOST" );

                if( RmaDAO.isRmaNoExists( dbTransaction, subform.getRmaNumber() ) )
			    {
                    errors.put( ERROR_RMA_NO_ALREADY_EXISTS, null );
                    request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
                    request.setAttribute( "generateRmaForm", subform );
			        request.setAttribute( "lineItems", getRmaLineItems() );
                    request.setAttribute( "mfgParts", SalesOrderDAO.loadAllManfacturingPartNumbers () );
                    dbTransaction.rollback();
                    return( mapping.findForward("success") );
                }
                rmaId = RmaDAO.saveRMADetails( dbTransaction, subform  );
                subform.setRmaId( rmaId );
                ArrayList rmaLineItems = new ArrayList();
                rmaLineItems = loadLineItems( request  );
                if( rmaLineItems.size() == 0 )
                {
                  rmaLineItems = getRmaLineItems();
                }

                RmaDAO.saveRMALineItemDetails( dbTransaction, subform, rmaLineItems  );

                success = true;
				if ( success == true )
                {
					dbTransaction.commit();
                    ArrayList rmaList = RmaDAO.getRmaLineItemDetails(Integer.toString(subform.getRmaId()));
                    subform.setLineItemList( rmaList );
                    sendMialToRMAUsers (subform , rmaList, user.getEmail(), host );
                    request.setAttribute ( "rmaId",Integer.toString(rmaId) );
                    info.put ( subform.getRmaNumber(), "Saved Successfully" );
                    info.put( "Email ", " has been send to the Internal Users" );
                    info.put( "View/Print ","Click here to <a href='javascript:openRMA();' onmouseover=\"window.status='Click here to View/print RMA Form';return true\" onmouseout=\"window.status='';return true\">  view/print  </a>  RMA Details");
				}
                else
                {
					dbTransaction.rollback();
				}

			}
            catch( Exception ex )
            {
				ex.printStackTrace();
			}
			if( !info.isEmpty() )
            {
                request.setAttribute(SessionKeys.INFO_MESSAGES,info);
            }
            request.setAttribute("customerList", CustomerDAO.getAllCustomerNames());

            return (mapping.findForward("rmaList"));
		}
        else if( "ConfirmForm".equals( action ) )
        {
            ArrayList rmaLineItems = new ArrayList();
            rmaLineItems = loadLineItems(request);
            if (rmaLineItems.size() == 0)
            {
                  rmaLineItems = getRmaLineItems();
            }
            subform.setEndUser( CustomerDAO.getCustomerName(null, subform.getEndUserID()));
            session.setAttribute("generateRmaForm",subform);
            session.setAttribute("lineItems", rmaLineItems );
            session.setAttribute("rmaId",Integer.toString(subform.getRmaId()));
            session.setAttribute("maxLineItemNo",request.getAttribute("maxLineItemNo"));
            return (mapping.findForward("confirmForm"));
        }
		else if( "SaveForm".equals( action ) )
        {
			try
            {
				DBTransaction dbTransaction = null;
				dbTransaction = DBTransaction.getInstance();
				dbTransaction.begin();
                String host = request.getHeader ( "HOST" );
                subform = (RMAForm) session.getAttribute("generateRmaForm");
                String status = null;
                boolean lineItemSuccess= false;
                status = ( (subform.getCloseDate() != null) && (subform.getCloseDate().length() != 0) ) ? "CLOSE" : "ISSUED" ;

                RmaDAO.updateRmaDetails( dbTransaction, subform, status );

                // RmaDAO.saveRMALineItemDetails(dbTransaction, subform, loadLineItems(request));
                lineItemSuccess= RmaDAO.saveRMALineItemDetails( dbTransaction, subform, ( ArrayList) session.getAttribute("lineItems") );

                /* Commented By Basha (03/02/2004)
				if((subform.getCloseDate() != null) && (subform.getCloseDate().length() != 0)){
					RmaDAO.updateRmaDetails(dbTransaction , subform);
				}
                */
				success = true;
				if( success == true )
                {
					dbTransaction.commit();
                    if( lineItemSuccess== true )
                    {
                        ArrayList rmaList = RmaDAO.getRmaLineItemDetails(Integer.toString(subform.getRmaId()));
                        subform.setLineItemList( rmaList );
                        sendMialToRMAUsers (subform , rmaList, user.getEmail(), host );
                        request.setAttribute("rmaId",Integer.toString(subform.getRmaId()));
                        request.setAttribute("rmaNo",subform.getRmaNumber());
					    info.put(subform.getRmaNumber(), "Saved Successfully");
                        info.put("Email ", " has been send to the User");
                        info.put("View/Print ","Click here to <a href='javascript:openRMA();' onmouseover=\"window.status='Click here to View/print RMA Form';return true\" onmouseout=\"window.status='';return true\">  view/print  </a>  RMA Details");
                    }
                    else
                    {
                        request.setAttribute("rmaId",Integer.toString(subform.getRmaId()));
                        request.setAttribute("rmaNo",subform.getRmaNumber());
					    info.put(subform.getRmaNumber(), "Saved Successfully");
                        info.put("View/Print ","Click here to <a href='javascript:openRMA();' onmouseover=\"window.status='Click here to View/print RMA Form';return true\" onmouseout=\"window.status='';return true\">  view/print  </a>  RMA Details");
                    }
                }
                else
                {
					dbTransaction.rollback();
				}
            }
            catch(Exception ex)
            {
				ex.printStackTrace();
			}

			if( !info.isEmpty() )
            {
                request.setAttribute(SessionKeys.INFO_MESSAGES,info);
            }

            session.removeAttribute("generateRmaForm");

            session.removeAttribute("rmaLineItems");
            session.removeAttribute("rmaId");
            session.removeAttribute("rmaBillingAddress");
            session.removeAttribute("maxLineItemNo");

          	request.setAttribute("customerList", CustomerDAO.getAllCustomerNames());

			return (mapping.findForward("rmaList"));
		}
        else if( "EditForm".equals( action ) )
        {

            subform = (RMAForm) session.getAttribute("generateRmaForm");

            request.setAttribute("rmaId" , Integer.toString(subform.getRmaId()));
			request.setAttribute("generateRmaForm",session.getAttribute("generateRmaForm"));
            request.setAttribute("lineItems",session.getAttribute("lineItems"));
            //request.setAttribute("mktgParts",SalesOrderDAO.loadAllMarketingPartNumbers());
            request.setAttribute ( "mfgParts", SalesOrderDAO.loadAllManfacturingPartNumbers () );
            request.setAttribute("rmaBillingAddress" , session.getAttribute("rmaBillingAddress") );
            request.setAttribute("maxLineItemNo", session.getAttribute("maxLineItemNo") );
            request.setAttribute("endUserList", CustomerRelationshipDAO.getOdmsForChangeSalesOrder( subform.getCustomerId()+"" , subform.getEndUserID()+""  ) );
            request.setAttribute( "vendorDetails", VendorDAO.getVendorNamesByProcessByUserType( null, Constants.LOCATION_TYPE_FINISHED_GOODS, null ) );

            HashMap VendorAddressMap = NewVendorLocationDAO.getVendorAddressDetailsMap(Constants.LOCATION_TYPE_FINISHED_GOODS);
            subform.setVendorAddressMap( VendorAddressMap );
            ArrayList list = ( ArrayList )request.getAttribute ( "lineItems"); //To Know whether atleast one line item is Closed, if so setting request attribute to False, otherwise True
            String rmaLineItemStatus = "";

            request.setAttribute( "rmaCanCancel", new Boolean ( true ) );

            for ( int i = 0; i < list.size(); i++ )
            {
                RMALineItem rmaLineItem = (RMALineItem)list.get(i);
                if ( rmaLineItem != null )
                {
                    rmaLineItemStatus = rmaLineItem.getStatus();
                    if ( "CLOSE".equalsIgnoreCase( rmaLineItemStatus ) )
                    {
                        request.setAttribute( "rmaCanCancel", new Boolean ( false ) );
                        break;
                    }
                }
            }
			return (mapping.findForward("rmaIssue"));
		}
        else if( "PrintRMA".equals( action ) )
        {
            String rmaId    = request.getParameter("rmaId");
            String cancel   = request.getParameter("cancel");

            SalesOrder salesOrder = new SalesOrder();
            String clientaddressId =  UserDAO.getClientAddressId();
            String addressId = null;
            String clientname = null;
            ArrayList list = null;

            int finalAddressId = 0;

            if( clientaddressId != null )
            {
                StringTokenizer st = new StringTokenizer(clientaddressId,"@");
                try
                {
                  addressId = st.nextToken();
                  clientname = st.nextToken();
                }catch(NoSuchElementException e)
                {
                   clientname  = "";
                }
            }
            if( addressId  != null)
            {
                finalAddressId = Integer.parseInt( addressId );
            }
            Address clientAddress= UserDAO.loadClientAddressDetails( null , finalAddressId );
            salesOrder.setClientAddressAsObject( clientAddress );
            String clientAddress1 = SalesOrder.getClientAddressAsString( clientAddress );
            salesOrder.setClientAddress( clientAddress1 );
            salesOrder.setClientName( clientname );

            request.setAttribute( "salesOrder", salesOrder );

            RmaDAO.getRmaDetails( subform, rmaId );
            request.setAttribute( "mfgParts", SalesOrderDAO.loadAllManfacturingPartNumbers() );

			list = RmaDAO.getRmaLineItemDetails( rmaId );
			if( !list.isEmpty() )
            {
				request.setAttribute( "lineItems", list);
			}else
            {
				request.setAttribute( "lineItems", getRmaLineItems() );
			}
            request.setAttribute( "rmaCancel", "YES".equalsIgnoreCase( cancel )? "YES":"NO" );
            request.setAttribute( "termsAndConditions", SalesDAO.loadTermsAndConditionsAsList() );

            return ( mapping.findForward( "printForm" ) );

        }
        else if( "CancelRMAForm".equals( action ) )
        {

            String rmaId = (String)request.getParameter("rmaId");
            String rmaNo = (String)request.getParameter("rmaNo");

            try
            {
				DBTransaction dbTransaction = null;
				dbTransaction = DBTransaction.getInstance();
				dbTransaction.begin();
                RmaDAO.cancelRmaForm(dbTransaction , rmaId );
                success = true;
                if(success == true)
                {
					dbTransaction.commit();
                    request.setAttribute("rmaId",rmaId);
                    info.put(rmaNo, "has been cancelled");
                    info.put("View/Print ","Click here to <a href='javascript:openRMA();' onmouseover=\"window.status='Click here to View/print Cancelled RMA Form';return true\" onmouseout=\"window.status='';return true\">  view/print  </a>  RMA Details");

				}
                else
                {
					dbTransaction.rollback();
				}
			}
            catch(Exception ex)
            {
				ex.printStackTrace();
			}
            if( !info.isEmpty() )
            {
                request.setAttribute(SessionKeys.INFO_MESSAGES, info);
            }

			return (mapping.findForward("rmaList"));
        }
        else if( "ApproveForm".equals( action ) )
        {
			try
            {
				DBTransaction dbTransaction = null;
				dbTransaction = DBTransaction.getInstance();
				dbTransaction.begin();
                boolean approveSucess = false;
                approveSucess= RmaDAO.saveRMAApprovedLineItemDetails(dbTransaction, subform.getLineItemList() );
                ArrayList list=subform.getLineItemList();
                String rmaId=null;
                for ( int i = 0; i < list.size(); i++ )
                {
                    RMALineItem rmaLineItem = (RMALineItem)list.get(i);
                    if ( rmaLineItem != null )
                    {
                        rmaId= Integer.toString(rmaLineItem.getRmaId());
                        break;
                    }
                }
				success = true;
				if( success == true )
                {
					dbTransaction.commit();
                    int countRMAApproved = 0;
                    int countLineItem = 0;
                    String host = request.getHeader ( "HOST" );
                    RmaDAO.getRmaDetails(subform, rmaId);
                    subform.setLineItemList(null);
                    ArrayList rmaList = RmaDAO.getRmaLineItemDetails(rmaId);
                    subform.setLineItemList( rmaList );
                    if (approveSucess)
                    {
                        for ( int i = 0; i < subform.getLineItemList().size(); i++ )
                        {
                            RMALineItem rmaLineItem = (RMALineItem)rmaList.get(i);
                            if ( rmaLineItem != null )
                            {
                                if ( rmaLineItem.getIsApproved() )
                                {
                                    countRMAApproved ++;
                                }
                                countLineItem++;
                            }
                        }
                        if( countRMAApproved == countLineItem )
                        {
                            RmaDAO.updateApproveRmaDetails(dbTransaction , subform , "APPROVED" );
                        }
                        sendMialToRMACustomers (subform , subform.getLineItemList(), user.getEmail(), host );
                        request.setAttribute("rmaId",Integer.toString(subform.getRmaId()));
                        request.setAttribute("rmaNo",subform.getRmaNumber());
                        info.put(subform.getRmaNumber(), "Approved Successfully");
                        info.put("Email ", " has been send to the customer");
                        info.put("View/Print ","Click here to <a href='javascript:openRMA();' onmouseover=\"window.status='Click here to View/print RMA Form';return true\" onmouseout=\"window.status='';return true\">  view/print  </a>  RMA Details");
                    }
                }
                else
                {
					dbTransaction.rollback();
				}

			}
            catch(Exception ex)
            {
				ex.printStackTrace();
			}

			if( !info.isEmpty() )
            {
                request.setAttribute(SessionKeys.INFO_MESSAGES,info);
            }
                                                                    
            session.removeAttribute("generateRmaForm");
            session.removeAttribute("rmaLineItems");
            session.removeAttribute("rmaId");
            session.removeAttribute("rmaBillingAddress");
            session.removeAttribute("maxLineItemNo");

            request.setAttribute("customerList", CustomerDAO.getAllCustomerNames());

			return (mapping.findForward("rmaList"));
		}
        /*if("ApproveForm".equals(action))
        {
            try
            {
                DBTransaction dbTransaction = null;
                dbTransaction = DBTransaction.getInstance();
                dbTransaction.begin();
               // subform= new RMAForm();
                //String host = request.getHeader ( "HOST" );
                System.out.println("subform.getRmaId() = " + subform.getLineItemList());
                RmaDAO.saveRMAApprovedLineItemDetails(dbTransaction, subform.getLineItemList() );
                int countRMAApproved = 0;
                int countLineItem = 0;
                //request.setAttribute( "rmaCanCancel", new Boolean ( true ) );

                //subform.setLineItemList(RmaDAO.getRmaLineItemDetails(Integer.toString(subform.getRmaId())));
                ArrayList list=subform.getLineItemList();
                String rmaId=null;
                for ( int i = 0; i < list.size(); i++ )
                {
                    RMALineItem rmaLineItem = (RMALineItem)list.get(i);
                    if ( rmaLineItem != null )
                    {
                        rmaId= Integer.toString(rmaLineItem.getRmaId());
                        break;
                    }
                }
                //RmaDAO.getRmaDetails(subform, rmaId);
                //RmaDAO.getRmaLineItemDetails(rmaId);
                for ( int i = 0; i < subform.getLineItemList().size(); i++ )
                {
                    RMALineItem rmaLineItem = (RMALineItem)list.get(i);
                    if ( rmaLineItem != null )
                    {
                        if ( !rmaLineItem.getIsApproved() )
                        {
                            countRMAApproved ++;
                        }
                        countLineItem++;
                    }
                }
                //subform.setLineItemList(RmaDAO.getRmaLineItemDetails(rmaId));
                System.out.println("countLineItem = " + countLineItem);
                System.out.println("countRMAApproved = " + countRMAApproved);
                if( countRMAApproved == countLineItem )
                {
                    //RmaDAO.updateApproveRmaDetails(dbTransaction , subform , "APPROVED" );
                }
                success = true;
                if( success == true )
                {
                    dbTransaction.commit();
                    request.setAttribute("rmaId",Integer.toString(subform.getRmaId()));
                    request.setAttribute("rmaNo",subform.getRmaNumber());
                    try
                    {
                        //sendMialToRMACustomers ( subform , list, user.getEmail(), host );
                        info.put(subform.getRmaNumber(), "Approved Successfully");
                        info.put("Email ", " has been send to the customer");
                        info.put("View/Print ","Click here to <a href='javascript:openRMA();' onmouseover=\"window.status='Click here to View/print RMA Form';return true\" onmouseout=\"window.status='';return true\">  view/print  </a>  RMA Details");
                    }
                    catch(Exception e)
                    {
                        info.put ( subform.getRmaNumber(), "Approved Successfully" );
                        errors.put ( "Email ", " has been Not sent to the customer" );
                        info.put ( "View/Print ","Click here to <a href='javascript:openRMA();' onmouseover=\"window.status='Click here to View/print RMA Form';return true\" onmouseout=\"window.status='';return true\">  view/print  </a>  RMA Details" );
                    }

                }else
                {
                    dbTransaction.rollback();
                }

            }
            catch(Exception ex)
            {
                ex.printStackTrace();
            }
            if(!info.isEmpty()) {
                request.setAttribute(SessionKeys.INFO_MESSAGES,info);
            }

            session.removeAttribute("generateRmaForm");
            session.removeAttribute("rmaLineItems");
            session.removeAttribute("rmaId");
            session.removeAttribute("rmaBillingAddress");
            session.removeAttribute("maxLineItemNo");

            request.setAttribute("customerList", CustomerDAO.getAllCustomerNames());

            return (mapping.findForward("rmaList"));
        }*/
        if( "ApproveRMAForm".equals( action ) )
        {

            String rmaId = (String)request.getParameter("rmaId");
            String rmaLineItemStatus = "";
            ArrayList list = null;

            RmaDAO.getRmaDetails(subform, rmaId);

            request.setAttribute ( "mfgParts", SalesOrderDAO.loadAllManfacturingPartNumbers () );

            list = RmaDAO.getRmaLineItemDetails(rmaId);

            request.setAttribute( "rmaCanCancel", new Boolean ( true ) );             //To Know whether atleast one line item is Closed, if so setting request attribute to False, otherwise True
            for ( int i = 0; i < list.size(); i++ )
            {
                RMALineItem rmaLineItem = (RMALineItem)list.get(i);
                if ( rmaLineItem != null )
                {
                    rmaLineItemStatus = rmaLineItem.getStatus();
                    if ( rmaLineItemStatus != null && rmaLineItemStatus.equalsIgnoreCase("CLOSE") )
                    {
                        request.setAttribute( "rmaCanCancel", new Boolean ( false ) );
                        break;
                    }
                }
            }

            if(!list.isEmpty())
            {
                request.setAttribute("lineItems", list);
                subform.setLineItemList(list);
            }
            Address address = CustomerDAO.getAddress(subform.getBillingAddressId());

            if (address == null){
                address = new Address();
            }

            session.setAttribute("rmaBillingAddress" , address );
            request.setAttribute("rmaId" , rmaId );
            request.setAttribute("endUserList", CustomerRelationshipDAO.getOdmsForChangeSalesOrder( subform.getCustomerId()+"" , subform.getEndUserID()+""  ) );
            session.setAttribute ( "vendorDetails", VendorDAO.getVendorNamesByProcessByUserType( null, Constants.LOCATION_TYPE_FINISHED_GOODS, null ) );
            HashMap VendorAddressMap = NewVendorLocationDAO.getVendorAddressDetailsMap(Constants.LOCATION_TYPE_FINISHED_GOODS );
            subform.setVendorAddressMap( VendorAddressMap );

            if( "ISSUED".equalsIgnoreCase( subform.getRmaStatus() ) )
            {
                return( mapping.findForward("approveForm") );
            }
        }
        // Report any errors we have discovered back to the original form
		if (!errors.isEmpty())
        {
			request.setAttribute(SessionKeys.ERROR_MESSAGES, errors);
		}

        // Forward control to the specified success URI
        return (mapping.findForward( "success" ) );
    }

    public ArrayList getRmaLineItems()
    {
    	ArrayList list = new ArrayList();
    	for(int i=0; i<=6; i++)
        {
    		RMALineItem lineItem = new RMALineItem();
            lineItem.setLineItemNo(i+1);
    		list.add(lineItem);
    	}
    	return list;
    }

    public ArrayList loadLineItems( HttpServletRequest request )
    {

    	ArrayList list = new ArrayList();
        int maxLineItemNo = 1;

    	String[] lineItemNo = request.getParameterValues("lineItemNo");
        String[] lineItemId = request.getParameterValues("lineItemId");
       	String[] partNumber = request.getParameterValues("partNumber");
    	String[] invoiceNumber = request.getParameterValues("invoiceNumber");
    	String[] invoiceDate = request.getParameterValues("invoiceDate");
    	String[] quantity = request.getParameterValues("quantity");
    	String[] problemDescription = request.getParameterValues("problemDescription");
    	String[] remarks = request.getParameterValues("remarks");

        String[] poLineItemNo = request.getParameterValues("poLineItemNo");
        String[] poNumber = request.getParameterValues("poNumber");
        String[] unitPrice = request.getParameterValues("unitPrice");

        String[] closeQty = request.getParameterValues("closeQty");

        String[] lineItemCloseDate = request.getParameterValues("lineItemCloseDate");
        String[] isClosed = request.getParameterValues("isClosed");
        String[] receiveQty = request.getParameterValues("receiveQty");
        String[] salesOderNo = request.getParameterValues("salesOrderNumber");
        String closedQuantity = null;
        String receiveQuantity = null;

        for(int i=0; i<lineItemNo.length; i++)
        {
    		RMALineItem lineItem = new RMALineItem();
    		if( ( partNumber[i] != null ) && ( partNumber[i].trim() != "" ) && ( partNumber[i].length() != 0 ) )
            {
            	lineItem.setLineItemNo(Integer.parseInt(lineItemNo[i].trim()));
                lineItem.setLineItemId(Integer.parseInt(lineItemId[i].trim()));
                lineItem.setPartNumber(partNumber[i]);
    			lineItem.setInvoiceNumber(invoiceNumber[i]);
    			lineItem.setInvoiceDate(invoiceDate[i]);
                closedQuantity = closeQty[i];

                if ( closedQuantity != null && !"".equalsIgnoreCase(closedQuantity.trim()) )
                {
                    lineItem.setCloseQty(Integer.parseInt(closedQuantity.trim()));
                }
                else
                {
                    lineItem.setCloseQty(0);
                }
                receiveQuantity = receiveQty[i];

                if ( receiveQuantity != null && !"".equalsIgnoreCase( receiveQuantity.trim() ) )
                {
                    lineItem.setReceiveQty( Integer.parseInt( receiveQuantity.trim() ) );
                } else
                {
                    lineItem.setReceiveQty( 0 );
                }

                lineItem.setLineItemCloseDate(lineItemCloseDate[i]);

                if ( "CLOSE".equalsIgnoreCase( isClosed[i] ) )
                {
                    lineItem.setStatus( isClosed[i] );
                    lineItem.setIsClosed( isClosed[i] );
                }

    			lineItem.setProblemDescription(problemDescription[i]);
    			lineItem.setRemarks(remarks[i]);
                lineItem.setSalesOrderNumber(salesOderNo[i]);

                int poLineItemNumber = Integer.parseInt(poLineItemNo[i].trim());
                String poNo = poNumber[i];

                lineItem.setPoLineItemNo(poLineItemNumber);
                lineItem.setPoNumber(poNo);

                try
                {

                    int qty = Integer.parseInt(quantity[i]);
                    //double price = Double.parseDouble(unitPrice[i].trim());
                    double price = RmaDAO.getPrice(poNo,poLineItemNumber,partNumber[i]);
                    // Prabhanjan (May 4 2004)
                    if(price == -1)
                    {
                        price = Double.parseDouble ( unitPrice[i] );
                    }

                    double amount = qty * price;


                    lineItem.setQuantity(qty);
                    lineItem.setUnitPrice(price);
                    lineItem.setExtendedPrice(amount);
                }
                catch(NumberFormatException nfe){
                    lineItem.setUnitPrice(0.0);
                    lineItem.setExtendedPrice(0.0);
                }


                lineItem.setIsExchange( ( request.getParameter("exchange"+i) != null ) ? true : false );
                lineItem.setIsCredit( ( request.getParameter("credit"+i) != null ) ? true : false );
                lineItem.setIsFa( ( request.getParameter("fa"+i) != null ) ? true : false );
                lineItem.setIsCancel( ( request.getParameter("cancel"+i) != null ) ? true : false );
                maxLineItemNo = (maxLineItemNo < lineItem.getLineItemNo()) ? lineItem.getLineItemNo() : maxLineItemNo;
                list.add(lineItem);
    		}
    	}
        request.setAttribute("maxLineItemNo",Integer.toString(maxLineItemNo+1));

    	return list;
    }
    public static void sendMialToRMACustomers(RMAForm subform1 , ArrayList rmaLineItemList, String from, String host)
    {
        String rmaAckFile = null;
        String[] mailAttachments = null;
        try
        {
            String to = CustomerDAO.getCustomerContactPersonEmailsForRMA( null, subform1.getCustomerId() );

            rmaAckFile = getRmaAckHtmlFile ( host, subform1, rmaLineItemList ) ;

            String subject = "RMA Acknowledgement for : " + subform1.getCustomerName();

            String message = "RMA Approved acknowledgement for " + subform1.getRmaNumber();

            if (from == null)
            {
                //from= ConfigManager.getSysAdminEmail ();
                from = ConfigManager.getFromEmailId(Constants.FROM_EMAIL_SALES_GROUP_NAME );
            }
            mailAttachments = new String[]{rmaAckFile};
            if(to!=null)
            {
                Mailer.send ( from, to, null, null , subject, message, mailAttachments, Mailer.CONTENT_TYPE_HTML, false );
            }
        }
        catch(Exception e)
        {
            String errMessage = "Internal Server Error";
            //errMessage.put ( errMessage, "Could not send Email" );
            e.printStackTrace ();
        }
    }
    
    public static String getRmaAckHtmlFile ( String host, RMAForm presentform, ArrayList rmaLineItemsList ) throws ScalarException
    {
        String filePath = null;
        String psAsHtml = SendRMAMailAction.formatAsHTML ( host, presentform, rmaLineItemsList );

        if ( psAsHtml == null )
        {
            return filePath;
        }

        FileWriter fWriter = null;
        File psAttachment = null;

        try
        {
            // CREATE TEMPORARY ATTACHMENT FILE
            File tempDir = new File ( "chiptrac_temp_dir" ).getCanonicalFile ();
            tempDir.mkdir ();

            String salesAttachmentFileName = null;
            String rmaNo = presentform.getRmaNumber ();
            salesAttachmentFileName = "RMA_ACK#  " + rmaNo + ".html";
            psAttachment = new File ( tempDir.getCanonicalPath (), salesAttachmentFileName );
            psAttachment.deleteOnExit ();

            if ( ( psAttachment.exists () == true ) || ( psAttachment.createNewFile () == true ) )
            {
                fWriter = new FileWriter ( psAttachment, false );

                fWriter.write ( psAsHtml );

                fWriter.close ();
                fWriter = null;

                filePath = psAttachment.getAbsolutePath ();
            }
        }
        catch ( Exception e )
        {
            System.out.println ( "Exception while creating RMA Ack html file" );
            e.printStackTrace ();
        }
        finally
        {
            if ( fWriter != null )
            {
                try
                {
                    fWriter.close ();
                    fWriter = null;
                }
                catch ( IOException ignore )
                {
                }
            }
        }

        return filePath;
    }
    public static void sendMialToRMAUsers(RMAForm subform1 , ArrayList rmaLineItemList, String from, String host)
    {
        String rmaAckFile           = null;
        String[] mailAttachments    = null;
        try
        {
            String to = UserDAO.getUsersEmailsForRMA(  null );

            String psAsHtml = SendRMAMailAction.formatAsHTML ( host, subform1, rmaLineItemList );
            String subject  = "RMA Acknowledgement for to All users " ;
            String message;
            //String message = "RMA Approved acknowledgement for " + subform1.getRmaNumber();
            if( psAsHtml != null )
            {
               message = psAsHtml;
            }
            else
            {
                message= "RMA Issued acknowledgement for " + subform1.getRmaNumber();
            }
            if( from == null )
            {
                //from = ConfigManager.getSysAdminEmail ();
                from = ConfigManager.getFromEmailId(Constants.FROM_EMAIL_SALES_GROUP_NAME );
            }
            //mailAttachments = new String[]{rmaAckFile};
            //System.out.println("from, to, null, null , subject, message, mailAttachments, Mailer.CONTENT_TYPE_HTML, false = " + from + to + subject + message + mailAttachments + Mailer.CONTENT_TYPE_HTML);
            Mailer.send ( from, to, null, null , subject, message, null, Mailer.CONTENT_TYPE_HTML, false );

        }
        catch(Exception e)
        {
            String errMessage = "Internal Server Error";
            System.out.println("errMessage = " + errMessage);

            //errMessage.put ( errMessage, "Could not send Email" );
            e.printStackTrace ();
        }
    }

}
